#include <buola/buola.h>

#if BUOLA_PLATFORM_LINUX

#include <buola/cv/io/cwebcam.h>
#include <buola/app/ceventloop.h>
#include <buola/image/io.h>
#include <buola/image/cgc.h>
#include <buola/app/ccmdline.h>
#include <buola/app/capp.h>
#include <buola/gui/ctoolkit.h>
#include <buola/widgets/cimagebox.h>

using namespace buola;

void OnImage(const img::CImage_rgb8 &pImage,gui::CImageBox &pBox)
{
    {
        msg_info() << "got one!\n";
        lock_guard<recursive_mutex> lLock(get_main_event_loop().GetMutex());
        pBox.SetImage(clone(pImage));
    }
}

int main(int pNArg,char **pArgs)
{
    buola_init(pNArg,pArgs);

    try
    {
        CApp lApp;
        
        gui::get_toolkit()->GetOpenGLGC()->MakeCurrent();

        //create the scene
        gui::PImageBox lBox=new gui::CImageBox;
        lBox->Map(CSize_d(800,600));
        
        cvi::CWebCam lWebCam(io::file("/dev/video0"));
        lWebCam.sImage.Connect([&](const img::CImage_rgb8 &pImage){   OnImage(pImage,*lBox);  });
        msg_info() << "getting one!\n";
        auto lImage=lWebCam.GetOne();
        msg_info() << "saving\n";
        msg_info() << "got one 2!\n";
        lWebCam.Start();
        
        msg_info() << "uuuu\n";
        
        lApp.Run();
    }
    catch(std::exception &pE)
    {
        msg_info() << "caught exception " << pE.what() << "\n";
    }

    return buola_finish();
}

#else
int main() {}
#endif